package cn.touna.jss.common.util;

import cn.touna.risk.api.http.HttpsKeyManager;
import cn.touna.risk.api.http.HttpsKeyStoreUtil;
import cn.touna.risk.api.http.HttpsSslContext;
import cn.touna.risk.api.http.HttpsTrustManager;
import org.apache.axis.components.net.JSSESocketFactory;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

/**
 *
 */
public class AxisTwoWayAuthSslSocketFactory extends JSSESocketFactory {

    public enum AttrKey {
        privateKeyPath, privateKeyPwd, keystorePath, keystorePwd;
    }

    private static String privateKeyPath;
    private static String privateKeyPwd;
    private static String keystorePath; //"E:\\developer\\workspace_idea\\gws\\gws-app\\src\\main\\resources\\properties\\pengyuan.keystore"
    private static String keystorePwd; // "123456"

    /**
     * Constructor JSSESocketFactory
     *
     * @param attributes
     */
    public AxisTwoWayAuthSslSocketFactory(Hashtable attributes) {
        super(attributes);
    }

    @Override
    protected void initFactory() throws IOException {
        HttpsKeyManager httpsKeyManager = new HttpsKeyManager(HttpsKeyStoreUtil.KeyStoreType.JKS, privateKeyPath, privateKeyPwd.toCharArray());
        HttpsTrustManager httpsTrustManager = new HttpsTrustManager(keystorePath, keystorePwd.toCharArray());
        HttpsSslContext context = new HttpsSslContext("TLS", httpsKeyManager, httpsTrustManager);
        sslFactory = context.getSSLContext().getSocketFactory();
    }

    public static void initConfig(Map<AttrKey, String> config) {
        AxisTwoWayAuthSslSocketFactory.privateKeyPath = config.get(AttrKey.privateKeyPath);
        AxisTwoWayAuthSslSocketFactory.privateKeyPwd = config.get(AttrKey.privateKeyPwd);
        AxisTwoWayAuthSslSocketFactory.keystorePath = config.get(AttrKey.keystorePath);
        AxisTwoWayAuthSslSocketFactory.keystorePwd = config.get(AttrKey.keystorePwd);
    }
}
